package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupPosition;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.SpliceAdapter;
import flc.ast.databinding.ActivityVideoSpliceBinding;
import flc.ast.utils.Content;
import flc.ast.utils.CustomAttachPopup;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;

public class VideoSpliceActivity extends BaseAc<ActivityVideoSpliceBinding> {


    public static List<String> listPath = new ArrayList<>();
    private long videoLength;
    private int playNum = 0;
    private SpliceAdapter splitAdapter;
    private int selPosition = 0;
    private CustomAttachPopup customAttachPopup;

    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_splice;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivVideoSpliceBack.setOnClickListener(v -> onBackPressed());
        mDataBinding.ivVideoSpliceAdd.setOnClickListener(this);
        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.ivVideoSpliceSave.setOnClickListener(this);
        mDataBinding.rvVideoSpliceList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        splitAdapter = new SpliceAdapter();
        mDataBinding.rvVideoSpliceList.setAdapter(splitAdapter);
        splitAdapter.addChildClickViewIds(R.id.ivVideoSpliceItemImg, R.id.ivVideoSpliceItemExchange);
        splitAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlayStart://播放
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.abofang);
                    mDataBinding.videoView.pause();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                    mDataBinding.videoView.start();
                }
                break;
            case R.id.ivPlayFull://放大
                PlayActivity.videoUri = listPath.get(playNum);
                startActivity(PlayActivity.class);
                break;
            case R.id.ivVideoSpliceAdd://添加
                Intent intent = new Intent(this, SelVideoActivity.class);
                intent.putExtra(Content.Again, "Again");
                startActivityForResult(intent, Content.SPLIT_ADD);
                break;
            case R.id.ivVideoSpliceSave://保存
                if (listPath.size() < 2) {
                    ToastUtils.showShort(getString(R.string.please_sel_two_video));
                    return;
                }
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.abofang);
                    mDataBinding.videoView.pause();
                }
                save();
                break;
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivVideoSpliceItemImg:
                playNum = position;
                splitAdapter.setCurrent(playNum);
                splitAdapter.notifyDataSetChanged();
                videoLength = MediaUtil.getDuration(listPath.get(playNum));
                mDataBinding.tvPlayLeft.setText("00:00");
                mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
                mDataBinding.videoView.setVideoPath(listPath.get(playNum));
                mDataBinding.videoView.seekTo(1);
                mDataBinding.videoView.start();

                customAttachPopup = new CustomAttachPopup(mContext);
                new XPopup.Builder(mContext)
                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .offsetX(-200) //偏移10
                        .offsetY(-180)  //往下偏移10
                        .popupPosition(PopupPosition.Top) //手动指定位置，有可能被遮盖
                        .hasShadowBg(false) // 去掉半透明背景
                        .atView(view)
                        .asCustom(customAttachPopup)
                        .show();
                customAttachPopup.setListener(new CustomAttachPopup.Ilistener() {
                    @Override
                    public void clickReplace() {
                        selPosition = position;
                        Intent intent = new Intent(VideoSpliceActivity.this, SelVideoActivity.class);
                        intent.putExtra(Content.Again, "Again");
                        startActivityForResult(intent, Content.SPLIT_REPLACE);
                    }

                    @Override
                    public void clickDelete() {
                        if (listPath.size() <= 1) {
                            ToastUtils.showShort(getString(R.string.just_have_one));
                            return;
                        }
                        listPath.remove(position);
                        updateData();
                        setPlayer();
                    }
                });
                break;
            case R.id.ivVideoSpliceItemExchange://交换视频
                if (position == listPath.size() - 1) {
                    ToastUtils.showShort(getString(R.string.not_video_exchange));
                    return;
                }
                Collections.swap(listPath, position, position + 1);
                updateData();
                setPlayer();
                break;
        }
    }

    @Override
    protected void initData() {
        if (listPath.size() == 0) return;
        updateData();
        //设置播放器
        setPlayer();
    }

    //更新集合
    private void updateData() {
        splitAdapter.setList(listPath);
        splitAdapter.setPos(listPath.size() - 1);
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        playNum = 0;
        splitAdapter.setCurrent(playNum);
        splitAdapter.notifyDataSetChanged();
        videoLength = MediaUtil.getDuration(listPath.get(0));
        mDataBinding.tvPlayLeft.setText("00:00");
        mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
        //设置播放器
        mDataBinding.videoView.setVideoPath(listPath.get(0));
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                playNum++;
                if (playNum < listPath.size()) {//继续播放下一个视频
                    splitAdapter.setCurrent(playNum);
                    splitAdapter.notifyDataSetChanged();
                    videoLength = MediaUtil.getDuration(listPath.get(playNum));
                    mDataBinding.tvPlayLeft.setText("00:00");
                    mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
                    mDataBinding.videoView.setVideoPath(listPath.get(playNum));
                    mDataBinding.videoView.seekTo(1);
                    mDataBinding.videoView.start();
                } else {//重新播放
                    setPlayer();
                }
            }
        });
        //开始播放视频
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mDataBinding.videoView.start();
    }

    //拼接视频
    private void save() {
        EditorHolder.editor().videoMerge(listPath, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                dismissDialog();
                FileP2pUtil.copyPrivateVideoToPublic(mContext, outFilePath);
                ToastUtils.showShort(getString(R.string.save_success));
                startActivity(HomeActivity.class);
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                ToastUtils.showShort(R.string.split_def);
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.split_ing) + progress + "%");
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        FileUtils.delete(PathUtils.getFilesPathExternalFirst() + Content.Temp);
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String path = data.getStringExtra(Content.videoPath);
            if (requestCode == Content.SPLIT_REPLACE) {
                listPath.set(selPosition, path);
            } else if (requestCode == Content.SPLIT_ADD) {
                listPath.add(path);
            }
            updateData();
            setPlayer();
        }
    }
}